package es.juanc.mail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GestorCorreo {

	private static Properties props = new Properties();
	private static Session mailSession;
	private static Message msg;
	private static Authenticator auth;

	/** Creates a new instance of GestorCorreo */
	public GestorCorreo() {

	}

	/**
	 * Configuramos los parametros de la cuenta de mail.
	 */
	public static void configuraCuenta() {
		props.put("mail.smtp.host", "smtp.micuenta.com");
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.auth", "true");
		props.setProperty("mail.user", "info@micuenta.com");
		props.setProperty("mail.password", "*****");
	}

	/**
	 * Establece una sesion dada la configuracion de la cuenta.
	 */
	public static void estableceSesion() {
		auth = new SMTPAuthenticator("info@micuenta.com", "*****");
		mailSession = Session.getInstance(props, auth);
	}

	public static void configuraMensaje() {
		try {
			msg = new MimeMessage(mailSession);
			msg.setSubject("Mensaje de Prueba");
			msg.setFrom(new InternetAddress("info@micuenta.com", "Mi cuenta"));
			msg.addRecipients(Message.RecipientType.TO,
					new InternetAddress[] { new InternetAddress("xoue82@gmail.com") });

		} catch (AddressException ex) {
			ex.printStackTrace();
		} catch (UnsupportedEncodingException ex) {
			ex.printStackTrace();
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
	}

	public static void textoMensaje() {
		try {
			DataHandler dh = new DataHandler("Mensaje de prueba", "text/plain");
			msg.setDataHandler(dh);
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
	}

	public static void enviaMensaje() {
		try {
			javax.mail.Transport.send(msg);
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
	}
}

class SMTPAuthenticator extends javax.mail.Authenticator {

	private String fUser;
	private String fPassword;

	public SMTPAuthenticator(String user, String password) {
		fUser = user;
		fPassword = password;
	}

	public PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(fUser, fPassword);
	}

}